import axios from 'axios';

// Define API base URL
const API_BASE_URL = 'http://localhost:8080';

// Login request interface
export interface LoginRequest {
  username: string;
  password: string;
  isMerchantLogin?: boolean;
}

// Login response interface
export interface LoginResponse {
  userId: string;
  customerId: string;
  username: string;
  token: string;
  isMerchant: boolean;
  merchantId?: string;
  avatar?: string;
}

// User register interface
export interface UserRegisterRequest {
  username: string;
  password: string;
  email: string;
  phone?: string;
  isMerchant?: boolean;
  merchantId?: string;
}

// User API service
export const userApi = {
  // User login
  login: async (loginData: LoginRequest) => {
    try {
      const response = await axios.post<{data: LoginResponse, code: number, message: string}>(
        `${API_BASE_URL}/api/user/login`, 
        loginData
      );
      return response.data;
    } catch (error) {
      console.error('Login failed:', error);
      throw error;
    }
  },

  // Merchant login
  merchantLogin: async (loginData: LoginRequest) => {
    try {
      const response = await axios.post<{data: LoginResponse, code: number, message: string}>(
        `${API_BASE_URL}/api/user/merchant/login`, 
        loginData
      );
      return response.data;
    } catch (error) {
      console.error('Merchant login failed:', error);
      throw error;
    }
  },

  // User registration
  register: async (userData: UserRegisterRequest) => {
    try {
      const response = await axios.post<{data: any, code: number, message: string}>(
        `${API_BASE_URL}/api/user/register`, 
        userData
      );
      return response.data;
    } catch (error) {
      console.error('Registration failed:', error);
      throw error;
    }
  },

  // Merchant registration
  registerMerchant: async (userData: UserRegisterRequest) => {
    try {
      const response = await axios.post<{data: any, code: number, message: string}>(
        `${API_BASE_URL}/api/user/merchant/register`, 
        userData
      );
      return response.data;
    } catch (error) {
      console.error('Merchant registration failed:', error);
      throw error;
    }
  },

  // Get user information
  getUserInfo: async (userId: string) => {
    try {
      const response = await axios.get<{data: any, code: number, message: string}>(
        `${API_BASE_URL}/api/user/${userId}`
      );
      return response.data;
    } catch (error) {
      console.error('Failed to get user information:', error);
      throw error;
    }
  }
}; 